package com.cn.ycy.controller;


import com.cn.ycy.config.Add;
import com.cn.ycy.config.Update;
import com.cn.ycy.config.Delete;
import com.cn.ycy.dto.Product;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;

/**
 * @Valid // Java自带的校验器，不支持组校验
 * @Validated // Spring 扩展的校验器，支持组校验
 */
@Controller
@RequestMapping("validate")
@Api(value = "参数校验功能")
//@Validated
/*
  重要：
  1 GET请求的参数校验必须放到Class类上
  2 如果 @Validated配置了 groups,那么校验注解必须增加指定groups，不然 校验注解 不生效
    举例： 使用 /add 设置price字段为-1，校验不生效
 */
public class ValidController {

  static Logger logger = LoggerFactory.getLogger(ValidController.class);

  @RequestMapping(value = "/add", method = RequestMethod.POST)
  @ResponseBody
  public Product add(@RequestBody @Validated(Add.class) Product product) {
    logger.info("{}", product);
    return product;
  }

  @RequestMapping(value = "/add2", method = RequestMethod.POST)
  @ResponseBody
  public Product add2(@RequestBody @Validated() Product product) {
    logger.info("{}", product);
    return product;
  }


  @RequestMapping(value = "/delete", method = RequestMethod.POST)
  @ResponseBody
  public Product delete(@RequestBody @Validated(Delete.class) Product product) {
    logger.info("{}", product);
    return product;
  }

  @RequestMapping(value = "/update", method = RequestMethod.POST)
  @ResponseBody
  public Product update(@RequestBody @Validated(Update.class) Product product) {
    logger.info("{}", product);
    return product;
  }

  @RequestMapping(value = "/get", method = RequestMethod.GET)
  @ResponseBody
  public Product get(@Min(1) @RequestParam("id") Integer id) {
    Product product = new Product();
    product.setId(Long.valueOf(id));
    return product;
  }


}
